﻿using Shiloh.Job.Model.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shiloh.Job.Repositories
{
    public class UserIndividualRepo
    {
        private Repository<UserIndividual> _repository;
        public ISqlSugarClient db;
        public UserIndividualRepo(Repository<UserIndividual> repository) {
            _repository = repository;
            db = _repository.Context;
        }

        /// <summary>
        /// 根据用户名获取实体
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<UserIndividual> GetEntityByUserName(string userName) {
            return await _repository.GetSingleAsync(it => it.Username.Equals(userName));
        }
        public async Task<UserIndividual> GetEntityByPhone(string phone)
        {
            return await _repository.GetSingleAsync(it => it.PhoneNumber.Equals(phone));
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<bool> CheckUserNameExist(string userName){
            return await _repository.IsAnyAsync(it => it.Username.Equals(userName));
        }

        public async Task<bool> UpdateUser(UserIndividual user) {
            return await _repository.UpdateAsync(user);
        }

        public async Task<bool> ClearLoginFailCount(Guid id)
        {
            return  await _repository.AsUpdateable()
                .SetColumns(it=>it.LoginFailCount == 0 && it.IsLocked == false)
                .Where(it=>it.Id.Equals(id))
                .ExecuteCommandAsync() > 0;
        }

        public async Task<bool> UnLock(Guid id)
        {
            return await _repository.AsUpdateable()
                .SetColumns(it => it.IsLocked == false)
                .Where(it => it.Id.Equals(id))
                .ExecuteCommandAsync() > 0;
        }
        public async Task<bool> Lock(Guid id)
        {
            return await _repository.AsUpdateable()
                .SetColumns(it => it.IsLocked == true)
                .Where(it => it.Id.Equals(id))
                .ExecuteCommandAsync() > 0;
        }

        public async Task UpdateLoginFailCount(Guid id)
        {
            await _repository.AsUpdateable().SetColumns(it => it.LoginFailCount == it.LoginFailCount + 1).ExecuteCommandAsync();
        }

        public async Task<UserIndividual> AddUser(UserIndividual userIndividual)
        {
            return await _repository.AsInsertable(userIndividual).ExecuteReturnEntityAsync();
        }
    }
}
